package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.exception.CatchCustomException;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.AppJwtUtil;
import com.usian.utils.common.BCrypt;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult login(WmUserDto dto) {
        // 判断参数
        if(dto==null){
            CatchCustomException.catchs(20003,"参数有误");
        }
        if(StringUtils.isEmpty(dto.getName())||StringUtils.isEmpty(dto.getPassword())){
            CatchCustomException.catchs(20003,"用户名或密码为空");
        }
        // 判断登录
        WmUser wmUser =  this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName,dto.getName()));
        if(wmUser==null){
            CatchCustomException.catchs(20003,"用户名有误！");
        }
        if(wmUser.getStatus()!=9){
            CatchCustomException.catchs(20003,"账号异常！");
        }
        // 通过bcypt
        if(!BCrypt.checkpw(dto.getPassword(),wmUser.getPassword())){
            //失败
            CatchCustomException.catchs(20003,"密码有误！");
        }
        // 修改最后登录时间
        wmUser.setLoginTime(new Date());
        updateById(wmUser);
        // 签发令牌
        String token =  AppJwtUtil.getToken(Long.parseLong(wmUser.getId()+""));
        Map<String,Object> resultMap = new HashMap<>();
        wmUser.setPassword("");
        resultMap.put("user",wmUser);
        resultMap.put("token",token);
        return ResponseResult.okResult(resultMap);
    }
}
